<?php
namespace Admin\Controller;

class PropertyController extends AdminController
{
    public function index()
    {
        $res = M('property')->field(array('onethink_property.*','onethink_goods.title'))->join("onethink_goods on onethink_property.gid = onethink_goods.id")->select();
        $this->assign('res', $res);
        $this->display();
    }

    public function update()
    {
        if (IS_POST) {
            $pic         = $this->upload();
            $_POST['pic'] = $pic;
            $id       = session('id');
            $property = D('property');
            $res2     = $property->create(I('post.'));
            if ($res2) {
                if ($property->where(array('id' => $id))->save()) {
                    session('id', null);
                    $this->success('修改成功！', U('index'));
                } else {
                    $this->error($property->getError());
                }
            } else {
                $this->error($property->getError());
            }
        } else {
            $id   = I('get.id');
            $res1 = M('goods')->select();
            $res  = M('property')->where(array('id' => $id))->select()[0];
            if ($res) {
                session('id', $id);
                $this->assign('res', $res);
                $this->assign('res1', $res1);
            }
            $this->display();
        }
    }

    public function delete()
    {
        $id  = I('get.id');
        $res = M('property')->where(array('id' => $id))->delete();
        if ($res) {
            $this->success('删除成功');
        } else {
            $this->error(M('property')->getError());
        }
    }

    public function add()
    {
        if (IS_POST) {
            $pic         = $this->upload();
            $_POST['pic'] = $pic;
            $property = D('property');
            $res2     = $property->create(I('post.'));
            if ($res2) {
                if ($property->add()) {
                    $this->success('添加成功！', U('index'));
                } else {
                    $this->error($property->getError());
                }
            } else {
                $this->error($property->getError());
            }
        } else {
            $res1 = M('goods')->select();
            $this->assign('res1', $res1);
            $this->display();
        }
    }

    public function upload()
    {
        $upload           = new \Think\Upload(); // 实例化上传类
        $upload->maxSize  = 3145728; // 设置附件上传大小
        $upload->exts     = array('jpg', 'gif', 'png', 'jpeg'); // 设置附件上传类型
        $upload->rootPath = '/Uploads/'; // 设置附件上传目录
        // 上传文件
        $info = $upload->upload();
        if (!$info) {
            // 上传错误提示错误信息
            $this->error($upload->getError());
        } else {
            // 上传成功
            $path = '';
            foreach($info as $v){
                $path .=$v['savepath'].$v['savename'].',';
            }
            return rtrim($path,',');
        }
    }
}
